package p10.code.exchanger;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Exchanger;

public class Producer implements Runnable{

    private final Exchanger<List<Integer>> exchanger;

    public Producer(Exchanger<List<Integer>> exchanger) {
        this.exchanger = exchanger;
    }

    @Override
    public void run() {
        List<Integer> message = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            try {
                Thread.sleep(1000);
                message.add(i);
                System.out.println(Thread.currentThread().getName() + ": 生产了数据[" + i + "]");
                message = exchanger.exchange(message);
                System.out.println(Thread.currentThread().getName() + ": 交换得到数据[" + String.valueOf(message.get(0)) + "]");
                message.remove(0);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}
